<html lang="en" xmlns:th="http://www.thymeleaf.org">

<div class="panel">
    <div class="panel-body">
        <ul id="tree_department" class="ztree"></ul>
    </div>
</div>

<script th:inline="javascript">

    var treeObj;
    var multi = [[${multi}]];
    var deptIds = [[${deptIds}]];

    $(function(){
        init_tree_department();
    });

    function init_tree_department(){
        var setting = {
            async: {
                enable: true,
                url:'/main/department/tree',
                autoParam: ['id'],
                type: 'get',
                dataType: 'json'
            },
            callback: {
                onAsyncSuccess: zTreeOnAsyncSuccess,
                onCheck: zTreeOnCheck
            },
            check : {
                enable: true,
                chkStyle : multi === "y" ? "checkbox" : "radio",
                radioType :"all",
                chkboxType:  { 'Y' : '', 'N' : '' }
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'pId',
                    rootPId: ''
                }
            },
            view: {
                autoCancelSelected: false,
                dblClickExpand: false,
                selectedMulti: true
            }
        };
        treeObj = $.fn.zTree.init($('#tree_department'), setting);
    }

    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        var zTree = $.fn.zTree.getZTreeObj('tree_department');
        if (treeNode) {
            for(var i=0; i<deptIds.length; i++){
                var node = zTree.getNodeByParam("id", deptIds[i]);
                if(node!=null){
                    zTree.checkNode(node,true,false);
                }
            }
        } else {
            var rootNode = zTree.getNodes()[0];
            if (rootNode.isParent) {
                zTree.expandNode(rootNode, true, true, true);
            }
        }
    }

    function zTreeOnCheck(event, treeId, treeNode){
//        console.log(treeNode.id + ", " + treeNode.name + "," + treeNode.checked);
    }

    function fn_dialog_departments_select(callback) {
//        var treeObj = $.fn.zTree.getZTreeObj('tree_department');
        var nodes = treeObj.getCheckedNodes();
        var deptNames = "";
        var deptIds = "";
        for(var i=0; i<nodes.length; i++){
            deptNames += nodes[i].name + ",";
            deptIds += nodes[i].id + ",";
        }
        deptNames = deptNames.substring(0,deptNames.length-1);
        deptIds = deptIds.substring(0,deptIds.length-1);
        callback({"name":deptNames,"id":deptIds});
    }

</script>

</html>